// gLance - Theme Changer

// To set / clear theme based on user preference
function setTheme()
{
    var positionPreferences = CordysRoot.document.getElementById("preferences");
    var userTheme = positionPreferences? positionPreferences.getProperty("theme") : null; 
	var existingTheme = getParam(top.location.href, "theme");

	if(!system.parameters[".caf"])
		system.parameters[".caf"] = new Object();
	system.parameters[".caf"]["theme"] = userTheme;

	if(!application.organization)
	{
		if(existingTheme)
			redirectSite(null, null);
	}	
	else
	{
		if( userTheme && (!existingTheme || (existingTheme != userTheme)))
			redirectSite(application.organization, userTheme);
		if(!userTheme && existingTheme)
			redirectSite(application.organization, null);
	}
}

// To redirect site with  specified organization and theme context
function redirectSite(organization, theme)
{
	var locationURL = top.location.href;
	locationURL = setParam(locationURL, "organization", organization);
	locationURL = setParam(locationURL, "theme", theme);
	top.location.replace(locationURL);
}

// To get parameter value from url
function getParam(url, key)
{
	var value = "";
	var queryString = url.split("#")[0].split("?")[1];
	if(queryString)
	{
		var params = queryString.split("&");
		for(var i=0; i<params.length; i++)
		{
			if(params[i].split("=")[0] == key)
			{
				value = params[i].split("=")[1];
				break;
			}
		}
	}
	return value;
}

// To set parameter value to url
function setParam(url, key, value)
{
	var hashSplit = url.split("#");
	var querySplit = hashSplit[0].split("?");
	var queryString = querySplit[1];
	var newParam = value ? (key + "=" + value) : "";
    if(queryString)
	{
		var params = queryString.split("&");
		var matchCount = 0;
		for(var i=0; i<params.length; i++)
		{
			if(params[i].split("=")[0] == key)
			{
				if(newParam)
				{
					params[i] = newParam;
					matchCount++;
					break;
				}
				else
				{
					params.splice(i, 1);
					matchCount++;
					break;
				}
			}
		}
		if(matchCount == 0 && newParam) params[params.length] = newParam;
		queryString = params.join("&");
	}
	else
	{
		queryString = newParam;
	}
	//  FORMAT:  baseURL + "?" + queryString + "#" + postURL
	return querySplit[0] + (queryString ? ("?" + queryString) : "") + (hashSplit[1] ? "#" + hashSplit[1] : "");
}
